// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import Star from "./star";
import {globalConfig} from "../config/globalConfig";
import {wxUtils} from "../wx/wxUtils";
import {utils} from "../utils/utils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Grade extends cc.Component {

  @property(cc.Label)
  labelName: cc.Label = null;

  @property([Star])
  stars: [Star] = []
  @property(cc.Sprite)
  icon: cc.Sprite = null;
  @property(cc.Node)
  newGradeNode:cc.Node = null;
  @property(cc.Node)
  btnShare: cc.Node = null;

  // LIFE-CYCLE CALLBACKS:

  onLoad () {
    this.newGradeNode.active = false;
    this.btnShare.active = false;
  }

  start() {

  }

  private currentGrade = 0;

  setGrade(num: number) {
    const config = globalConfig.Grade[num - 1];
    this.setStar(config.star)
    this.labelName.string = config.name
    this.currentGrade = num;
    this.setIconId(config.iconid);
    if(this.isUpgrade()) {
      this.btnShare.active = true;
      this.newGradeNode.active = true;
    }
  }

  addGrade() {
    this.setGrade(this.currentGrade + 1)
  }

  private setStar(value: number) {
    this.stars.forEach(value1 => value1.bright = false)
    this.stars.forEach((value1, index) => {
      if (index < value) {
        value1.bright = true
      }
    })
  }

  onShareTouch() {
    wxUtils.shareToFriends()
  }

  setIconId(iconId: number) {
    this.icon.node.active = false;
    cc.loader.loadRes(`icon/icon_duanWei${iconId}`, (err, res) => {
      this.icon.spriteFrame = new cc.SpriteFrame(res);
      this.icon.node.active = true;
    });
  }

  private lastConfig: any = null;

  /**
   * 是否升段
   * @returns {boolean}
   */
  private isUpgrade() {
    if (this.currentGrade <= 5) {
      return false;
    }
    return (this.currentGrade - 1) % 5 === 1
  }

}
